package club.dataresources.util;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 使用google map
 *
 * @author Tao
 */
public class GoogleLocationUtil {
    private String googleApiKey;
    private String amapApiKey;
    private final String EN = "en";
    private final String ZH_CN = "zh-CN";

    public GoogleLocationUtil() {
        FileInputStream in;
        Properties prop = new Properties();
        ClassLoader classLoader = getClass().getClassLoader();
        URL url = classLoader.getResource("config.properties");
        try {
            in = new FileInputStream(url.getFile());
            prop.load(in);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        googleApiKey = prop.getProperty("googleApiKey");
        amapApiKey = prop.getProperty("amapApiKey");
    }


    /**
     * 获取地址
     *
     * @param lat      纬度
     * @param lng      经度
     * @param language 返回的语言，如简体中文(zh-CN),美式英文(en)
     * @return 地址
     */
    public String getAddress(double lat, double lng, String language) {
        String address = "";
        if (EN.equals(language)) {
            //TODO 英文版使用google地图接口
        } else if (ZH_CN.equals(language)) {
            //中文版使用高德地图接口
            String apiUrl = "http://restapi.amap.com/v3/geocode/regeo?location=" + lng + "," + lat + "&key=" + amapApiKey;
            try {
                URL url = new URL(apiUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("GET");
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line;
                StringBuilder result = new StringBuilder();
                while ((line = in.readLine()) != null) {
                    result.append(line).append("\n");
                }
                JSONObject res = new JSONObject(result.toString());
                JSONObject regeocode = res.getJSONObject("regeocode");
                in.close();
                address = regeocode.getString("formatted_address");
                return address;
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
        }
        return address;
    }

    /**
     * 获取城市
     *
     * @param latitude  纬度
     * @param longitude 经度
     * @return 城市, 如上海, 广州
     */
    public static String getCity(String latitude, String longitude) {
        //TODO 需要重写
        return "";
    }

    /**
     * 根据正则表达式匹配城市
     *
     * @param address 地址
     * @return 省, 市,
     */
    public static List<Map<String, String>> addressResolution(String address) {
        String regex = "(?<province>[^省]+省|.+自治区)(?<city>[^自治州]+自治州|[^市]+市|[^盟]+盟|[^地区]+地区|.+区划)(?<county>[^市]+市|[^县]+县|[^旗]+旗|.+区)?(?<town>[^区]+区|.+镇)?(?<village>.*)";
        Matcher m = Pattern.compile(regex).matcher(address);
        String province, city, county, town, village;
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> row;
        while (m.find()) {
            row = new LinkedHashMap<String, String>();
            province = m.group("province");
            row.put("province", province == null ? "" : province.trim());
            city = m.group("city");
            row.put("city", city == null ? "" : city.trim());
            county = m.group("county");
            row.put("county", county == null ? "" : county.trim());
            town = m.group("town");
            row.put("town", town == null ? "" : town.trim());
            village = m.group("village");
            row.put("village", village == null ? "" : village.trim());
            list.add(row);
        }
        return list;
    }
}
